//
//  WXTool.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/4.
//  Copyright © 2016年 郑东喜. All rights reserved.
//

import UIKit



class WXTool : NSObject,WXApiDelegate {
    // MARK:- 将类设计成单例
    static let shareIntance : WXTool = WXTool()
    
//    lazy manager = AFHTTPSessionManager()
    lazy var manager = AFHTTPSessionManager()
    
    func setupWX() -> Void {
        
    }
    
    
    func onReq(_ req: BaseReq!) {
        print(#function)
    }

    func onResp(_ resp: BaseResp!) {
        let strTitle = "支付结果"
        var strMsg = "\(resp.errCode)"
        
        if resp.isKind(of: PayResp.self) {
            
            switch resp.errCode {
            case 0:
                strMsg = "支付成功"
            default:
                strMsg = "支付失败,请您重新支付!"
                print("retcode = \(resp.errCode),retstr = \(resp.errCode)")
            }
            
            let alert = UIAlertView(title: strTitle, message: strMsg, delegate: nil, cancelButtonTitle: "好的")
            alert.show()
            
        }
        
        if resp.isKind(of: SendMessageToWXResp.self) {
            switch resp.errCode {
            case 0:
                let alertController = UIAlertController(title: "提示", message: "分享成功", preferredStyle: UIAlertControllerStyle.alert)
                
                
                alertController.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.default, handler: nil))
                
                UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
                
                break
            default:
                
                let alertController = UIAlertController(title: "提示", message: "分享成功", preferredStyle: UIAlertControllerStyle.alert)
                
                
                alertController.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.default, handler: nil))
                
                UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
                break;
            }
        }
        
        if (resp is SendAuthResp) {
            let temp = (resp as! SendAuthResp)
            var accessUrlStr = "\(WX_BASE_URL)/oauth2/access_token?appid=\(WXPatient_App_ID)&secret=\(WXPatient_App_Secret)&code=\(temp.code)&grant_type=authorization_code"
            accessUrlStr = accessUrlStr.addingPercentEscapes(using: String.Encoding.utf8)!

            self.manager.get(accessUrlStr, parameters: nil, success: { (task, responseObject) in
                
//                
//                let accessDict = responseObject as! [String :AnyObject]
//                let accessToken = (accessDict[WX_ACCESS_TOKEN] as! String)
//                
//                let openID = (accessDict[WX_OPEN_ID] as! String)
//                let refreshToken = (accessDict[WX_REFRESH_TOKEN] as! String)
                let accessDict = JSON(responseObject : responseObject!)
                let accessToken = accessDict[WX_ACCESS_TOKEN]
                let openID = accessDict[WX_OPEN_ID]
                let refreshToken = accessDict[WX_REFRESH_TOKEN]
                
                
                // 本地持久化，以便access_token的使用、刷新或者持续
                
                if (accessToken != "") as Bool! && (accessToken != "") && (openID != "") as Bool! && !(openID != "") {
                    UserDefaults.standard.set(accessToken, forKey: WX_ACCESS_TOKEN)
                    UserDefaults.standard.set(openID, forKey: WX_OPEN_ID)
                    UserDefaults.standard.set(refreshToken, forKey: WX_REFRESH_TOKEN)
                    UserDefaults.standard.synchronize()
                }
                self.wechatLoginByRequestForUserInfo()
                
                
            }, failure: { (task, error) in
                print("获取access_token时出错 = \(error)")
                
            })
        }
    }
    
    func wechatLoginByRequestForUserInfo() -> Void {
        let accessToken = UserDefaults.standard.object(forKey: WX_ACCESS_TOKEN)
        let openID = UserDefaults.standard.object(forKey: WX_OPEN_ID)
        var userUrlStr = "\(WX_BASE_URL)/userinfo?access_token=\(accessToken)&openid=\(openID)"
        
        userUrlStr = userUrlStr.addingPercentEscapes(using: String.Encoding.utf8)!
        self.manager.get(userUrlStr, parameters: nil, success: { (task, responseObject) in
            print("\((#file as NSString).lastPathComponent):(\(#line))")
            
            let json = JSON(responseObject : responseObject!)
            print(json)
            
        }) { (task, error) in
            print("获取用户信息时出错 = \(error)")
            
        }
    }
}

extension WXTool {
    func clickAuto() -> Void {
        let accessToken = UserDefaults.standard.object(forKey: WX_ACCESS_TOKEN)
        let openID = UserDefaults.standard.object(forKey: WX_OPEN_ID)
        // 如果已经请求过微信授权登录，那么考虑用已经得到的access_token
        if (accessToken != nil) && (openID != nil) {
            let refreshToken = UserDefaults.standard.object(forKey: WX_REFRESH_TOKEN)!
            var refreshUrlStr = "\(WX_BASE_URL)/oauth2/refresh_token?appid=\(WXPatient_App_ID)&grant_type=refresh_token&refresh_token=\(refreshToken)"
            refreshUrlStr = refreshUrlStr.addingPercentEscapes(using: String.Encoding.utf8)!
            
            self.manager.get(refreshUrlStr, parameters: nil, success: { (task, responseObject) in
                

//                var refreshDict = responseObject as! [String :AnyObject]
//                let reAccessToken = (refreshDict[WX_ACCESS_TOKEN] as! String)
                
                let refreshDict = JSON(responseObject : responseObject!)
                let reAccessToken = refreshDict[WX_ACCESS_TOKEN]
                
                // 如果reAccessToken为空,说明reAccessToken也过期了,反之则没有过期
                if (reAccessToken == "") {
                    
//                    UserDefaults.standard.set(reAccessToken, forKey: WX_ACCESS_TOKEN)
//                    UserDefaults.standard.set((refreshDict[WX_OPEN_ID] as! String), forKey: WX_OPEN_ID)
//                    UserDefaults.standard.set((refreshDict[WX_REFRESH_TOKEN] as! String), forKey: WX_REFRESH_TOKEN)
                    
                    UserDefaults.standard.set(refreshToken, forKey: WX_ACCESS_TOKEN)
                    UserDefaults.standard.set(refreshDict[WX_OPEN_ID], forKey: WX_OPEN_ID)
                    UserDefaults.standard.set(refreshDict[WX_REFRESH_TOKEN], forKey: WX_REFRESH_TOKEN)
                    UserDefaults.standard.synchronize()
                    //        self.backClosure = tempClosure

                } else {
                    self.wechatLogin()
                }
            }, failure: { (task, error) in
                print("用refresh_token来更新accessToken时出错 = \(error)")
            })
        } else {
            wechatLogin()
        }
    }
    
    
    func wechatLogin() {
        if WXApi.isWXAppInstalled() {
            let req = SendAuthReq()
            req.scope = "snsapi_userinfo"
            req.state = "GSTDoctorApp"
            WXApi.send(req)
        }
        else {
            self.setupAlertController()
        }
    }
    
    
    func setupAlertController() {
        let alert = UIAlertController(title: "温馨提示", message: "请先安装微信客户端", preferredStyle: .alert)
        let actionConfirm = UIAlertAction(title: "确定", style: .default, handler: nil)
        alert.addAction(actionConfirm)
        UIApplication.shared.keyWindow?.rootViewController?.present(alert, animated: true, completion: { _ in })
    }
    
    func share() -> Void {
        let req = SendMessageToWXReq()
        req.text = "简单文本分享测试"
        req.bText = true
        // 目标场景
        // 发送到聊天界面  WXSceneSession
        // 发送到朋友圈    WXSceneTimeline
        // 发送到微信收藏  WXSceneFavorite
        req.scene = Int32(WXSceneFavorite.rawValue)
        WXApi.send(req)
    }
}
